package com.inossem.warehousestorage_inossem.activity.in_storage.chuangyou;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.utils.log.LogUtils;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.in_storage.extra.InStorageExtra;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStorageCheckPositionRequestBean;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStoragePositionInformationBean;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStorageShoppingListBean;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStorageShoppingListRequestBean;
import com.inossem.warehousestorage_inossem.bean.inStorage.chuangyou.CYInStorageShoppingOverviewBean;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.inStorage.chuangyou.CYInStorgaeCheckPositionRequest;
import com.inossem.warehousestorage_inossem.request.inStorage.chuangyou.CYInStorgaeShoppingListRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.CYInStorageUtils;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author 王斯宇
 * @time on 2018/3/28 11:17
 * @email siyu.wang@inossem.com
 */
public class CYInStorageShoppingDetailActivity extends BaseActivity {

    private TextView title ,batch, materialDescribe, materialCode, location, arrivalNumber , unit;

    private PercentLinearLayout positionLayout;

    private int id;//动态添加的仓位view的id

//    private List<Integer> viewId;//存放动态添加的仓位view的id

    private String itemId , locationId;

    private EditText position;

    private ImageView search;

    private List<CYInStoragePositionInformationBean.PositionBean> positionBeanList;


    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        super.onCreateImpl(savedInstanceState);
        setContentView(R.layout.cy_activity_in_storage_shopping_detail);
        initView(CYInStorageShoppingDetailActivity.this);
        initData(CYInStorageShoppingDetailActivity.this);
    }
    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        batch = (TextView) activity.findViewById(R.id.batch);
        materialDescribe = (TextView) activity.findViewById(R.id.materialDescribe);
        materialCode = (TextView) activity.findViewById(R.id.materialCode);
        location = (TextView) activity.findViewById(R.id.location);
        arrivalNumber = (TextView) activity.findViewById(R.id.arrivalNumber);
        positionLayout = (PercentLinearLayout) activity.findViewById(R.id.positionLayout);
        position = (EditText) activity.findViewById(R.id.position);
        search = (ImageView) activity.findViewById(R.id.search);
        unit = (TextView) activity.findViewById(R.id.unit);

    }
    private void initData(Activity activity) {
        title.setText(R.string.cy_activity_in_storage_shopping_overview_title);
        ActivityUtils.initBackAndFunction(activity, getResources().getString(R.string.activity_receive_result_back), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String result = checked();
                if (TextUtils.isEmpty(result)) {
                    CYInStorageUtils.sortingPosition(CYInStorageShoppingDetailActivity.this , positionBeanList , itemId);
                    finish();
                }else {
                    Utils.middleToast(CYInStorageShoppingDetailActivity.this , result);
                }
            }
        });

        search.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (!TextUtils.isEmpty(position.getText().toString())) {
                    if (!CYInStorageUtils.havePosition(positionBeanList , position.getText().toString())) {
                        checkPosition(activity , position.getText().toString());
                    }else{
                        Utils.middleToast(activity ,"该仓位已经存在");
                    }
                }
                Utils.closeSoftKeyboard(activity , v);
            }
        });
        getExtras();
        getData(activity);
        setmScanListener((String scanResult, int length) -> {
            switch (QRCodeUtils.getQRCodeType(scanResult)) {
                case QRCodeConstant.CY_TYPE_POSITION:
                    String mCondition = QRCodeUtils.DecryptQRCode(scanResult , QRCodeConstant.CY_BATCH_PARAMETER_BATCH);
                    if (!CYInStorageUtils.havePosition(positionBeanList , mCondition)) {
                        checkPosition(activity , mCondition);
                    }else{
                        Utils.middleToast(activity ,"该仓位已经存在");
                    }
                    break;
                default:
                    Utils.middleToast(activity , "扫描码类型错误");
                    break;
            }

//            mCondition = QRCodeUtils.DecryptQRCode(scanResult);
//            getData(activity, mCondition, mFactoryCode, mInventoryAddressCode, mBusinessType, mSpecialInventory);
        }, QRCodeConstant.CY_TYPE_POSITION);

    }

    private void getExtras () {
        itemId = getIntent().getStringExtra(InStorageExtra.ITEM_ID);
    }

    private void getData (Context context) {
        CYInStorageShoppingOverviewBean.ItemBean.ItemListBean bean = CYInStorageUtils.getDetailByItemId(context , itemId);
        batch.setText(bean.getBatch());
        materialDescribe.setText(bean.getMat_name());
        materialCode.setText(bean.getMat_code());
        location.setText(bean.getLocation_code() + "-" + bean.getLocation_name());
        arrivalNumber.setText(bean.getQty());
        unit.setText(bean.getName_zh());
        locationId = bean.getLocation_id();
        positionBeanList = bean.getPositionBeanList() == null ? new ArrayList<>() : bean.getPositionBeanList();

        for (int i = 0; i < positionBeanList.size(); i++) {
            addPosition(positionBeanList.get(i) , positionBeanList.get(i).getInStorageNumber() , i);
            LogUtils.i("positionBeanList.viewID ========= " + positionBeanList.get(i).getPositionViewId());
        }
        id = positionBeanList.size();
//        viewId = new ArrayList<>();
    }
    private void addPosition (CYInStoragePositionInformationBean.PositionBean positionBean , String count , int view_id) {
        CYInStorageUtils.createEditText(CYInStorageShoppingDetailActivity.this ,positionLayout , positionBean.getPositionCode() , count , unit.getText().toString() , view_id , new CYInStorageShoppingDetailListener() {
            @Override
            public void deleteClickListener(int id , String positionCode) {
//                for (int i = 0; i < viewId.size(); i++) {
//                    if (viewId.get(i) == id) {
//                        viewId.remove(i);//把删除的仓位从list中移除
//                        positionLayout.removeView(findViewById(id));
//                        break;
//                    }
//                }
                for (int i = 0; i < positionBeanList.size(); i++) {
                    if (positionBeanList.get(i).getPositionCode().equals(positionCode)) {
                        positionBeanList.remove(i);
                        positionLayout.removeView(findViewById(id));
                        break;
                    }
                }
            }
        });
//        viewId.add(id);

    }
    private void checkPosition (Context context , String position) {
        CYInStorageCheckPositionRequestBean bean = CYInStorageUtils.getAllocatingGetListRequestBean(locationId , position);
        CYInStorgaeCheckPositionRequest.request(context, bean, new GsonBeanListener<CYInStoragePositionInformationBean>() {
            @Override
            public void onSuccess(CYInStoragePositionInformationBean bean) {
                CYInStoragePositionInformationBean.PositionBean allData = bean.getBody();
                if (allData==null ) {
                    Utils.middleToast(context, getResources().getString(R.string.activity_in_storage_receive_list_no_message));
                    return;
                }
                allData.setPositionCode(position);
                allData.setPositionViewId(id);
                positionBeanList.add(allData);
                addPosition(allData , "0" ,id);
                id += 1;

            }
        });
    }
    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        String result = checked();
        if (TextUtils.isEmpty(result)) {
            LogUtils.i("save _positionBeanList.size ========= " + positionBeanList.size());
            CYInStorageUtils.sortingPosition(CYInStorageShoppingDetailActivity.this , positionBeanList , itemId);
            finish();
        }else {
            Utils.middleToast(CYInStorageShoppingDetailActivity.this , result);
        }
    }
    private String checked () {
        String result = null;
        float count = 0;
        for (int i = 0; i < positionBeanList.size(); i++) {
            View view = findViewById(positionBeanList.get(i).getPositionViewId());//查询仓位存放id的list中的仓位
            EditText editText = (EditText) view.findViewById(R.id.text);
            count += TextUtils.isEmpty(editText.getText().toString()) ? 0 : Float.parseFloat(editText.getText().toString());
            positionBeanList.get(i).setInStorageNumber(TextUtils.isEmpty(editText.getText().toString()) ? "0" :editText.getText().toString());
        }
//        if (count < Float.parseFloat(arrivalNumber.getText().toString())) {
//            return "入库数量小于到货数量";
//        }
        if (count > Float.parseFloat(arrivalNumber.getText().toString())) {
            return "入库数量不能大于到货数量";
        }
        return result;
    }

    public interface CYInStorageShoppingDetailListener {
        void deleteClickListener(int id , String positionCode);
    }
}
